package com.example.event_resource_java.authority.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.event_resource_java.authority.dao.JzPermission;
import com.example.event_resource_java.authority.dao.UserDao;
import com.example.event_resource_java.authority.mapper.JzPermissionMapper;
import com.example.event_resource_java.authority.mapper.resourceLibrary.SecretKeyMapper;
import com.example.event_resource_java.authority.server.IJzPermissionService;
import com.example.event_resource_java.commons.domain.UserDO;
import com.example.event_resource_java.commons.util.JWTUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Objects;

/**
 * <p>
 * 资源库前台权限表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-29
 */
@Service
public class JzPermissionServiceImpl extends ServiceImpl<JzPermissionMapper, JzPermission> implements IJzPermissionService {

    @Resource
    private JzPermissionMapper jzPermissionMapper;
    @Resource
    private UserDao userDao;
    @Resource
    private SecretKeyMapper secretKeyMapper;

    @Override
    public Boolean judge(JzPermission jzPermission) {
        Long userId = JWTUtil.getUser().getId();
        UserDO userDO = userDao.selectById(userId);
        if (userDO.getType() == 0) {
            userId = secretKeyMapper.getTeacherById(userId);
        }

        QueryWrapper<JzPermission> queryWrapper = new QueryWrapper<JzPermission>()
                .eq("allocation_id", jzPermission.getAllocationId())
                .eq("type", jzPermission.getType())
                .eq("user_id", userId);
        JzPermission permission = jzPermissionMapper.selectOne(queryWrapper);
        if (Objects.isNull(permission)) {
            return false;
        }

        String[] permissions = permission.getGroupType().split(",");
        return Arrays.asList(permissions).contains(jzPermission.getGroupType());
    }
}
